<template>
  <div>
    <el-container>
      <el-header>
        <div style="text-align: center; font-size: 25px; font-weight: bolder">
          <i class="el-icon-s-home" style="margin-right: 25px"></i>
          茶叶嫩芽检测系统
        </div>
      </el-header>
      <el-main>
        <el-card class="login-module" shadow="hover">
          <div slot="header" class="clearfix">
            <span
              style="
                text-align: center;
                font-size: 20px;
                font-family: 'Microsoft YaHei';
              "
            >
              <p v-if="!isLogin">
                <i
                  class="el-icon-office-building"
                  style="margin-right: 18px"
                ></i
                >登陆
              </p>
              <p v-else>
                <i class="el-icon-edit-outline" style="margin-right: 18px"></i
                >注册
              </p>
            </span>
          </div>
          <div>
            <el-form
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="账号" prop="name">
                <el-input
                  v-model.number="ruleForm.name"
                  placeholder="请输入账号"
                  prefix-icon="el-icon-lollipop"
                ></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="ruleForm.password"
                  placeholder="请输入密码"
                  show-password
                  prefix-icon="el-icon-ice-cream-round"
                ></el-input>
              </el-form-item>
              <!-- 随机验证码 -->
              <el-form-item
                v-if="!isLogin"
                label="验证码"
                prop="verifycode"
                style="line-height: 0px"
                class="verifycodeBox"
              >
                <el-input
                  v-model="ruleForm.verifycode"
                  ref="verifycode"
                  placeholder="验证码"
                  class="identifyinput"
                  style="width: 230px"
                ></el-input>
                <div
                  style="cursor: pointer"
                  class="identifybox"
                  @click="refreshCode"
                >
                  <sidentify :identifyCode="identifyCode"></sidentify>
                </div>
              </el-form-item>
              <el-form-item
                label="用户类型"
                prop="userType"
                class="userTypeBox"
              >
                <el-radio-group v-model="ruleForm.userType">
                  <el-radio label="user" value="user">用户</el-radio>
                  <el-radio label="admin" value="admin" v-if="!isLogin"
                    >管理员</el-radio
                  >
                  <el-radio label="admin" value="admin" disabled v-if="isLogin"
                    >管理员(不可注册)</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-form-item class="buttonBox">
                <el-button
                  type="primary"
                  @click="login('ruleForm')"
                  v-if="!isLogin"
                  >登陆</el-button
                >
                <el-button
                  type="primary"
                  @click="register('ruleForm')"
                  v-if="isLogin"
                  >注册</el-button
                >
                <el-button type="primary" @click="resetForm('ruleForm')"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div class="bottom">
            <p v-if="!isLogin" @click="isLogin = !isLogin">没有账号？去注册</p>
            <p v-else @click="isLogin = !isLogin" :style="{ color: '#409eff' }">
              已有账号？去登录
            </p>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import sidentify from "@/components/sidentify.vue";

export default {
  data() {
    return {
      ruleForm: {
        name: null,
        password: null,
        userType: null,
        verifycode: "",
      },
      identifyCodes: "1234567890", //验证码的数字库
      identifyCode: "", // 验证码组件传值
      rules: {
        name: [
          { required: true, message: "请输入账号", trigger: "blur" },
          // { type: "number", message: "请输入数字", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        verifycode: [
          {
            required: true,
            trigger: "blur",
            validator: this.validateVerifycode,
          },
        ],
        userType: [
          { required: true, message: "请选择用户类型", trigger: "change" },
        ],
      },
      isLogin: false,
    };
  },
  components: { sidentify },
  created() {
    this.refreshCode(); //初始化验证码
  },
  mounted() {
    // 验证码初始化
    this.identifyCode = "";
    this.makeCode(this.identifyCodes, 4);
  },

  methods: {
    // 验证码自定义验证规则
    validateVerifycode(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (value !== this.identifyCode) {
        console.log("验证码:", value);
        callback(new Error("验证码不正确!"));
      } else {
        callback();
      }
    },

    //验证码----start
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
      // console.log("this.identifyCode:", this.identifyCode);
    },
    //验证码----end

    //登录
    login(formName) {
      const that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // if (that.ruleForm.userType === "user") {
          //   sessionStorage.setItem("userType", "user");
          // } else {
          //   sessionStorage.setItem("userType", "admin");
          // }

          // sessionStorage.setItem(
          //   "userData",
          //   JSON.stringify({
          //     name: that.ruleForm.name,
          //     role: that.ruleForm.userType,
          //   })
          // );

          // that.$router.push("/" + that.ruleForm.userType);
          // return;

          if (that.ruleForm.userType == "user") {
            axios
              .post("http://localhost:8080/user/login", {
                name: that.ruleForm.name,
                password: that.ruleForm.password,
                userType: that.ruleForm.userType,
              })
              .then((res) => {
                if (res.code == 1) {
                  this.$message({
                    type: "success",
                    message: "登陆成功！欢迎" + that.ruleForm.name + "光临！",
                  });
                  // sessionStorage.setItem("type", that.ruleForm.userType);
                  sessionStorage.setItem("userData", JSON.stringify(res.data));
                  that.$router.push("/" + that.ruleForm.userType);
                } else {
                  this.$message({
                    type: "error",
                    message: "登录失败！请联系管理员",
                  });
                }
              });
          }
          if (that.ruleForm.userType == "admin") {
            axios
              .post("http://localhost:8080/admin/login", {
                name: that.ruleForm.name,
                password: that.ruleForm.password,
                userType: that.ruleForm.userType,
              })
              .then((res) => {
                if (res.code == 1) {
                  this.$message({
                    type: "success",
                    message: "登陆成功！欢迎" + that.ruleForm.name + "光临！",
                  });
                  // sessionStorage.setItem("type", that.ruleForm.userType);
                  sessionStorage.setItem("userData", JSON.stringify(res.data));
                  that.$router.push("/" + that.ruleForm.userType);
                } else {
                  this.$message({
                    type: "error",
                    message: "登录失败！请联系管理员",
                  });
                }
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //注册
    register(formName) {
      const that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (that.ruleForm.userType == "user") {
            axios
              .post("http://localhost:8080/user/register", {
                name: that.ruleForm.name,
                password: that.ruleForm.password,
                userType: that.ruleForm.userType,
              })
              .then((res) => {
                if (res.code == 1) {
                  this.$message({
                    type: "success",
                    message: "注册成功！",
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: "注册失败！请联系管理员",
                  });
                }
              });
          }
          if (that.ruleForm.userType == "admin") {
            axios
              .post("http://localhost:8080/admin/register", {
                name: that.ruleForm.name,
                password: that.ruleForm.password,
                userType: that.ruleForm.userType,
              })
              .then((res) => {
                if (res.code == 1) {
                  this.$message({
                    type: "success",
                    message: "注册成功！",
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: "注册失败！请联系管理员",
                  });
                }
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-container {
  height: 100vh;
  background-color: #e9eef3;
  // background: url("~@/assets/imgs/login_bg.png") center / 100% 100% no-repeat;
  // background: linear-gradient(to bottom right, #ff0000, #00ff00, #0000ff);
  //  animation: fadeIn 2s infinite;
  .el-header {
    background-color: #b3c0d1;
    color: #333;
    line-height: 60px;
  }
  .login-module {
    margin: 100px auto 0;
    width: 35%;
    padding: 0 30px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    // background: url("~@/assets/imgs/login_bg.png") center / 100% 100% no-repeat;
    /deep/.el-card__body {
      // width: 100%;
    }

    .verifycodeBox {
      display: flex;
      justify-content: space-between;
      /deep/.el-form-item__content {
        display: flex;
        justify-content: space-between;
        margin-left: 0 !important;
      }
    }
    .userTypeBox {
      display: flex;
      /deep/.el-form-item__content {
        .el-radio-group {
          margin-left: -20px;
          // margin-left: 5px;
        }
      }
    }

    .buttonBox {
      width: 100%;
      display: flex;
      justify-content: space-around;
      /deep/.el-form-item__content {
        margin-left: 0 !important;
      }
    }
    .bottom {
      p {
        font-size: 12px;
        color: #fa8646;
        text-align: right;
        cursor: pointer;
      }
    }
  }
}
</style>
